import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ModalDirective} from "ngx-bootstrap";
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from '@angular/forms';
import {EditorComponent} from '../../comm-components/wangeditor/editor.component';
import {NzMessageService} from "ng-zorro-antd";

import {AliyunOssOutputUrl, adSystemApiUrl,tuikeSystemUrl,couponsUrl} from "../../../config/api";
import {HttpService} from "../../lib/service/http.service";
import {Headers, RequestOptions} from "@angular/http";
import * as moment from 'moment';
import {ActivatedRoute, Router} from "@angular/router";
import {AdOssUploadService} from "../../lib/service/ad-oss-upload.service";
import {LoginService} from "../../lib/service/tuike-login.service";

@Component({
  selector: 'discovery',
  templateUrl: './discovery.component.html',
  styleUrls: ['./discovery.component.scss']
})
export class DiscoveryComponent implements OnInit {
  validateForm: FormGroup;
  validateForm1:FormGroup;
  validateSendForm:FormGroup;
  activity_type;
  active_type;
  _isSpinning=  false;

  tabs=[{
    name:"好物推荐",
    value:1
  },{
    name:"免费试用",
    value:2
  },{
    name:"领券中心",
    value:3
  },{
    name:"浪花社区",
    value:4
  },{
      name:"秒杀活动",
      value:5
    }
  ];
  @ViewChild(EditorComponent) editor: EditorComponent;
  state="";
  title="";
  titleSearch="";
  stateSearch="";
  stateList=[{
    value:"",
    name:"全部"
  },{
    value:"1",
    name:"启用中"
  },{
    value:"0",
    name:"已暂停"
  }];
  orderBy="created_at";
  orderList=[{
    value:"created_at",
    name:"按时间排序"
  },{
    value:"like_num",
    name:"按点赞数量"
  },{
    value:"view_num",
    name:"按浏览数量"
  }];
  categoryList=[];//浪花社区分类列表
  categoryList1=[];//选择活动
  catePage=1;
  catePageSize=5;
  typeVisible=false;
  cateTotal=0;
  sendVisible = false;

  canVisit = false;
  canVisit1 = false;
  canVisit2 = false;
  canVisit3 = false;


  addcate(){
    this.typeVisible=true;
    console.log("this.categoryList",this.categoryList);
    if(this.categoryList.length==0){
      this.catePage=1;
      this.getcategoryList();
    }
  }
  catepageChanged(e){
    this.catePage=e;
    this.getcategoryList();
  }
  getcategoryList1(){
    let url=`${tuikeSystemUrl}/api/v1/admin/activity_category_find/index?`;
    let json={
      page:1,
      pageSize:100
    };
    this.httpService.httpPostAuth(url,json).subscribe(res => {
      if (res.code === 200) {
        let data=res.data;
        this.categoryList1=data.data;
      }
    });
  }
  getcategoryList(type=null){
    let url=`${tuikeSystemUrl}/api/v1/admin/activity_category_find/index?`;
    let json={
      page:this.catePage,
      pageSize:this.catePageSize
    };
    this.httpService.httpPostAuth(url,json).subscribe(res => {
      if (res.code === 200) {
        let data=res.data;
        this.categoryList=data.data;
        this.cateTotal=data.total;
      }
    });
  }
  addtype=true;
  _submitForm1(data=null){//添加分类
    if (!this.addtype) {
      return;
    }
    let controls=this.validateForm1.controls;

    if (controls['category_name'].value.trim()){
      this.addtype = false;
    }else{
      this._message.create('error',"请输入分类名称");
      return false;
    }

    let json={
      title:controls['category_name'].value
    };
    let url=`${tuikeSystemUrl}/api/v1/admin/activity_category_find/create`;

    this.postEdit(url,json,(res)=>{
      this.addtype=true;
    });
  }
  postEdit(url,json,call){
    this.httpService.httpPostAuth(url,json).subscribe(res => {
      if (typeof call=='function') {
        call(res);
      }
      if (res.code === 200) {
        this._message.create('success',"保存成功");
        let category_name=null;
        this.validateForm1.patchValue({
          category_name
        });

        this.catePage=1;
        this.getcategoryList1();
        this.getcategoryList();
      }else{
        this._message.create('error',res.message);
      }
    });
  }
  closeType(){
    this.typeVisible=false;
  }
  editType(data){
    data.edit=true;
    data.titleValue=data.title;
  }
  saveEdit(data){
    if(data.saving){
      return false;
    }
    if (!data.titleValue.trim()) {
      this._message.create('error',"请输入分类名称");
      return false;
    }
    data.saving=true;
    let json={
      title:data.titleValue,
      id:data.id
    };
    let url=`${tuikeSystemUrl}/api/v1/admin/activity_category_find/update`;

    this.postEdit(url,json,(res)=>{
      data.saving=false;
      if(res.code==200){
        data.title=data.titleValue;
        data.edit=false;
      }
    });
  }
  canceleditType(data){
    data.edit=false;
  }

  confirmTypeDel(id){
    let url=`${tuikeSystemUrl}/api/v1/admin/activity_category_find/delete?id=`+id;
    this.httpService.httpGet(url).subscribe(res => {
      if (res.code==200) {
        if (this.categoryList.length==1&&this.catePage>1) {
          this.catePage=this.catePage-1;
        }
        this.getcategoryList();
        this.getcategoryList1();
        this._message.create('success',"删除成功");
      }else{
        this._message.create('error',res.message);
      }
    });
  }
  orderDesc="desc";
  data=[];
  total=0;
  isVisible=false;
  isVisibleWatch=false;
  watchContent="<div>sfwfwfe</div>";
  constructor(private adOssUploadService:AdOssUploadService,
        private loginService: LoginService,
        private _message: NzMessageService,
              private element:ElementRef,
              private httpService: HttpService,
              private el: ElementRef,
              private router: Router,
              private fb: FormBuilder,
              private route: ActivatedRoute) {
  }
  _disabledStartDate = (startValue) => {
    if (!startValue || !this.validateForm.controls.validity_end.value) {
      return false;
    }
    return startValue.getTime() >= this.validateForm.controls.validity_end.value.getTime();
  };
  _disabledEndDate = (endValue) => {
    if (!endValue || !this.validateForm.controls.validity_start.value) {
      return false;
    }
    return endValue.getTime() <= this.validateForm.controls.validity_start.value.getTime();
  };
  closeWatch(){
    this.watchContent="";
    this.isVisibleWatch=false;
  }
  openWatch(id){
    this.isVisibleWatch=true;
    this.getDetail(id,(res)=>{
      if (res.code === 200) {
        let flag = res.data.content.indexOf('[') === 0;
        if(flag) {
          JSON.parse(res.data.content).map((e,i) => {
            this.watchContent +=e.content;
          })
        } else {
          this.watchContent=res.data.content;
        }
      }
    });
  }
  type=1;
  changeOrder(value){
    console.log(value);
    console.log(this.orderBy);
    this.page=1;
    this.getList();
  }
  changeType(value){
    let item=this.tabs[value.index];
    this.type=item.value;
    let validateForm=this.validateForm;
    if(this.type==3&&!validateForm.controls['user_num_limit']){
      this.getCardList();
      validateForm.addControl('user_num_limit', this.fb.control(null, [Validators.required,Validators.pattern('^[0-9]+$')] ));
      validateForm.addControl('card_coupons_uuid', this.fb.control(null, [Validators.required] ));
    }else if(this.type==4&&!validateForm.controls['category_id']){
      this.getcategoryList1();
      validateForm.addControl('category_id', this.fb.control(null, [Validators.required] ));
    }else if(this.type!=3&&this.type!=4){
      validateForm.removeControl('user_num_limit');
      validateForm.removeControl('card_coupons_uuid');
      validateForm.removeControl('category_id');
    }
    this.page = 1;
    this.getList();
  }
  cardList=[];
  cardListObj={};
  getCardList(){
    let url=`${adSystemApiUrl}/v1/admin/coupon/card_coupons_all`;
    this.httpService.httpGetAuth(url).subscribe(res => {
      if (res.code === 200) {
        let data=res.data;
        this.cardList=data.map(item=>{
          let json={
            label:item.card_coupons_name+"("+(item.merchants_name)+")",
            value:item.card_coupons_uuid,
            app_key:item.app_key,
            merchants_id:item.merchants_id
          };
          this.cardListObj[item.card_coupons_uuid]=json;
          return json;
        })
      }else{

      }
    });
  }
  ceshi(obj){
    console.log(obj);
  }
  add(){
    this.router.navigate(['tuike/discovery/add_activity'],{
      queryParams:{
        type:this.type
      }
    });
    // this.id="";
    //this.editor.ceshi();
     //this.editor.changedEitorUsePlace('article');
    // this.editor.loadingHandle("");
    // let json={
    //   is_top:1,
    //   title:"",
    //   pic_url:["pic"],
    //   validity_end:null,
    //   validity_start:null,
    //   user_num_limit:"",
    //   card_coupons_uuid:null,
    //   category_id:null
    // };
    // if(this.type!=3){
    //   delete json.user_num_limit;
    //   delete json.card_coupons_uuid;
    // }else{
    //   this.card_disabled=false;
    // }
    // if(this.type!=4){
    //   delete json.category_id;
    // }

    // this.openVisible(json);
  }
  openVisible(json){
    this.isVisible=true;
    let validateForm = this.validateForm;

    validateForm.patchValue(json);
  }
  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }

  getFormControl1(name) {
    return this.validateSendForm.controls[ name ];
  }
  card_disabled=false;
  addStatus=true;
  descError=false;
  _submitForm(){ //添加活动保存
    console.log("this.addStatus:",this.addStatus);
    if (!this.addStatus) {
      return;
    }
    let controls=this.validateForm.controls;
    for (const i in this.validateForm.controls) {

      controls[i].markAsDirty();
    }

    let desc = this.editor.clickHandle();
    if(desc=="<p><br></p>"){
      this.descError = true;
      return false;
    }else{
      this.descError = false;
    }
    console.log("this.validateForm.valid:",this.validateForm.valid);
    if (this.validateForm.valid){
      this.addStatus = false;
    }else{
      return false;
    }
    console.log(33333);
    let url=`${tuikeSystemUrl}/api/v1/admin/activity_find/create?`;

    let validity_start=moment(controls["validity_start"].value).format('YYYY-MM-DD HH:mm:ss');
    let validity_end=moment(controls["validity_end"].value).format('YYYY-MM-DD HH:mm:ss');
    let title=controls['title'].value;
    let content=desc;
    let is_top=controls['is_top'].value;
    let type=this.type;
    let json={
      validity_start,
      validity_end,
      title,
      content,
      is_top,
      type,
      pic_url:"",
      id:"",
      user_num_limit:"",
      card_coupons_uuid:"",
      category_id:"",
      app_key:"",
      merchant_id:""
    };
    if(type==3){
      let list=this.cardListObj;
      json.user_num_limit=controls['user_num_limit'].value;
      let item=list[ controls['card_coupons_uuid'].value ];

      json.card_coupons_uuid= item.value;
      json.app_key=item.app_key;
      json.merchant_id=item.merchants_id;
      delete json.category_id;
    }else if(type==4){
      json.category_id=controls['category_id'].value;
      delete json.user_num_limit;
      delete json.card_coupons_uuid;
      delete json.app_key;
      delete json.merchant_id;
    }else{
      delete json.user_num_limit;
      delete json.card_coupons_uuid;
      delete json.category_id;
      delete json.app_key;
      delete json.merchant_id;
    }
    let pic_url_arr=controls['pic_url'].value;
    console.log(pic_url_arr);

    if(!pic_url_arr[0].url){
      this.adOssUploadService.getSignature2(`/api/v1/common/upload`, '/v1/member/discovery/edit', pic_url_arr[0], null)
          .subscribe(res => {
              if (res.code === 200) {
                json.pic_url=res.data[0];
                this.saveDiscovery(json);
              }else{
                this._message.create('error',res.message);
                this.addStatus=true;
              }
            }
          );
    }else{
      json.pic_url=pic_url_arr[0].url;
      this.saveDiscovery(json);
    }
  }
  openEdit(id,detail?){
    let params = {};
    if(detail) {
      params = {
        id:id,
        type:this.type,
        page:this.page,
        detail:true
      }
    } else {
      params = {
        id:id,
        type:this.type,
        page:this.page,
      }
    }
    this.router.navigate(['tuike/discovery/add_activity'],{
      queryParams:params
    });
    // this.getDetail(id,(res)=>{
    //   if (res.code === 200) {
    //     let data=res.data;
    //     let json={
    //       is_top:data.is_top,
    //       title:data.title,
    //       pic_url:[{url:data.pic_url,src:AliyunOssOutputUrl+data.pic_url}],
    //       validity_end:new Date(data.validity_end),
    //       validity_start:new Date(data.validity_start),
    //       user_num_limit:data.user_num_limit,
    //       card_coupons_uuid:data.card_coupons_uuid,
    //       category_id:data.category_id
    //     };
    //     this.fileList=[{url:data.pic_url,src:AliyunOssOutputUrl+data.pic_url}] ;
    //     if(data.type!=3){
    //       delete json.user_num_limit;
    //       delete json.card_coupons_uuid;
    //     }else if(data.state==2){
    //       this.card_disabled=false;
    //     }else{
    //       this.card_disabled=true;
    //     }
    //     if(data.type!=4){
    //       delete json.category_id;
    //     }
    //
    //     this.editor.loadingHandle(data.content);
    //     this.openVisible(json);
    //   }
    // })
  }
  getDetail(id,call){
    let url =`${tuikeSystemUrl}/api/v1/admin/activity_find/detail?id=`+id;
    this.id=id;
    this.httpService.httpGetAuth(url).subscribe(res => {
      if(typeof call=='function'){
        call(res);
      }
    })
  }
  id="";
  saveDiscovery(json){

    let url=`${tuikeSystemUrl}/api/v1/admin/activity_find/create?`;
    if(this.id){
      url=`${tuikeSystemUrl}/api/v1/admin/activity_find/update?`;
      json.id=this.id;
    }else{
      delete json.id;
    }

    this.httpService.httpPostAuth(url,json).subscribe(res => {
      this.addStatus=true;
      if (res.code === 200) {

        this._message.create('success','添加成功');
        // this.isVisible=false;
        // this.validateForm.reset();
        this.handleCancel();
        if(this.id){
          this.getList();
        }else{
          this.page=1;
          this.getList();
        }
      }else{

        this._message.create('error',res.message);

      }
    })

  }
  handleCancel(){
         this.isVisible=false;
         this.fileList=["pic"];
        this.validateForm.reset();

  }
  handleOk(){

  }
  page=1;
  pageSize=10;
  category_id="";
  getList(){
    let page=this.page;
    let pageSize=this.pageSize;
    let orderBy=this.orderBy;
    let order=this.orderDesc;
    let type=this.type;
    let url=`${tuikeSystemUrl}/api/v1/admin/activity_find/index?`;

    let json={
      type,
      page,
      pageSize,
      orderBy,
      order,
      title:this.titleSearch.trim()||"",
      state:this.stateSearch.trim()||"",
      category_id:""
    };

    if (this.type==4) {
      json.category_id=this.category_id;
    }

    let topObj=["不置顶","置顶"];
    this.httpService.httpPostAuth(url,json).subscribe(res => {
      if (res.code === 200) {
        let data=res.data.data;
        data.forEach(item=>{
          item.topName=topObj[item.is_top];
          item.pic_url=AliyunOssOutputUrl+item.pic_url;
        });
        console.log(res.data.total);
        this.total=res.data.total;
        this.data=data;
      }
    })
  }
  confirm(id){
    let url=`${tuikeSystemUrl}/api/v1/admin/activity_find/delete?id=`+id;
    this.httpService.httpGetAuth(url).subscribe(res => {
      if (res.code === 200) {
        this._message.create('success',"删除成功");
        if (this.data.length==1&&this.page>1) {
          this.page=this.page-1;
        }
        this.getList();
      }else{
        this._message.create('error',res.message);
      }
    })
  }
  pageChanged(e){
    console.log(e);
    this.page=e;
    this.getList();
  }
  editStatus = false;
  fileList=[];
  picError = false;//图片是否错误
  fileChange(list) {
    console.log('gggg');
    console.log(list);
    setTimeout(_ => {
      this.validateForm.patchValue({
        pic_url:list
      });
      this.validateForm.controls[ 'pic_url' ].updateValueAndValidity();
      this.validateForm.controls[ 'pic_url' ].markAsDirty();
    });
    // this.uploadImg1();
  }
  picChange(where) {
    setTimeout(_ => {
      this.validateForm.controls[ 'pic_url' ].updateValueAndValidity();
      this.validateForm.controls[ 'pic_url' ].markAsDirty();
    });
  }
  // wangEdit编辑器
  PostData(event): void {
     console.log(event);
  }
  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    console.log("control:",control)
    if (!control.value||!control.value[0]) {
      return { required: true };
    } else if (control.value[0]=="pic") {
      console.log('fefefe');
      return { required: true, error: true };
    }
  };

  ngOnInit() {
    this.route.snapshot.queryParams['type'] ? this.type = +this.route.snapshot.queryParams['type'] : '';
    this.route.snapshot.queryParams['page'] ? this.page = +this.route.snapshot.queryParams['page'] : '';
    this.canVisit = this.loginService.canVisitCheck('add_discovery_activity');
    this.canVisit2 = this.loginService.canVisitCheck('edit_discovery_activity');
    this.canVisit1 = this.loginService.canVisitCheck('add_push');
    this.canVisit3 = this.loginService.canVisitCheck('delete_discovery');
    // this.initTemplateInfo();
    //this.editor.changedEitorUsePlace('article');
    this.validateForm1=this.fb.group({
      category_name:["",[Validators.required]]
    });
    this.fileList=["pic"];
    this.validateForm = this.fb.group({
      title: [ "", [ Validators.required ] ],
      validity_end:[null,[Validators.required]],
      validity_start:[null,[Validators.required]],
      pic_url:[["pic"],[Validators.required,this.confirmationValidator]],
      is_top:[1,[Validators.required]]
    });

    // this.validateSendForm = this.fb.group({
    //   title:['',[Validators.required]],
    //   send_time:['',[null, Validators.required]]
    // });
    this.validateSendForm = this.fb.group({
      title:new FormControl('',[Validators.required]),
      send_time:new FormControl('',[Validators.required]),
      // activity_type: new FormControl(null, [Validators.required]),
      // send_time:['',[null, Validators.required]]
    });

    this.getList();
  }
  reset(){

    this.getList();
  }
  search(){
    this.titleSearch=this.title;
    this.stateSearch=this.state;
    this.getList();
  }

  keyDown(e) {
    if(e.code == 'Enter') {
      this.search();
    }
  }

  changeStatus(id,status) {
    status == 1 ? status = 0 : status = 1;
    console.log(status);
    let url = `${tuikeSystemUrl}/api/v1/admin/activity_find/change_status`;
    let json = {
      id:id,
      status:status
    };
    this.httpService.httpPostAuth(url, json).subscribe(res => {
      if (res.code === 2000) {
        this._message.create('success',status == 0 ? '暂停成功':'开启成功');
        this.getList();
      } else {
        this._message.create('error','改变状态失败');
      }
    });
  }



  goAdd(id) {
    this.router.navigate(['tuike/discovery/add'],{
      queryParams:{
        id:id,
        type:this.type
      }
    });
  }

  sendCancel(e) {
    this.sendVisible = false;
  }
  sendOk(e) {
    this.sendVisible = true;
  }

  _submitSendForm() {
    console.log(this.validateSendForm.value);
  }

  // initTemplateInfo(activity_id) {
  //   const url = `${tuikeSystemUrl}/api/v1/admin/wechat_message_send/send_index`;
  //   const headers = new Headers({'Content-Type': 'application/json'});
  //   const options = new RequestOptions({headers: headers});
  //   const body = JSON.stringify({'activity_id': activity_id});
  //   this.httpService.httpPostAuth(url,body,options).subscribe(res => {
  //    if(res.code === 200) {
  //      console.log(res.data.type);
  //      if(!this.activity_type) {
  //        res.data.type.map((e,i) => {
  //          this.activity_type.push({
  //            label:e,
  //            value:i
  //          })
  //        })
  //      }
  //    }
  //   })
  // }

}
